import axios from 'axios'
import { Toast } from 'vant';
import router from "./router"
import commonStore from "./store/common";

axios.defaults.baseURL = process.env.VUE_APP_BASE_URL
const instance = axios.create()

instance.interceptors.request.use(
    config => {
        config.headers["X-Requested-With"] = 'XMLHttpRequest'
        const token = localStorage.getItem(process.env.VUE_APP_TOKEN)
        //console.log('拦截请求token:',token)
        if (token) {
            config.headers["token"] = token
        }
        return config
    },
    err => {
        return Promise.reject(err)
    }
)

instance.interceptors.response.use(
    response => {
        if(response.headers?.token){
            const common = commonStore()
            common.token = response.headers.authorization
            localStorage.setItem(process.env.VUE_APP_TOKEN, response.headers.token)
        }
        if(response.data.code == -101){
            localStorage.removeItem(process.env.VUE_APP_STORAGENAME)
            localStorage.removeItem(process.env.VUE_APP_TOKEN)
            commonStore.token = null
            commonStore.userInfo = []
            router.replace({ path: '/login' })
        }
        if(response.data.code != 200){
            if(response.data.code != 301){
                Toast.fail(response.data.msg);
            }
            return Promise.reject({code: response.data.code, msg: response.data.msg});
        }
        return response.data
    },
    err => {
        let msg = err.response?.data?.message ? err.response.data.message : '太火爆了，稍后再试'
        Toast.fail(msg);
        return Promise.reject({ code: 0, msg: msg })
    }
)

export default instance
